package openjdk.jdk;

import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;

/**
 * Created by Asin Liu on 2017/2/23.
 */
public class ScannerMain {

    public static void main(String[] args) {
        ssout("");
    }


    /**
     * The default delimiter used by the Scanner is whitespace.
     * It returns text tokens separated by whitespace. Let us use this fact to count the words in a file.
     * The following code prints the value as well as its index from the file.
     * Note that the Scanner implements the AutoCloseable interface so we can use it in try-with-resources block.
     *
     * @param file
     */
    private static void ssout(String file) {
        try (Scanner scanner = new Scanner(new File(file))) {
            int nword = 0;
            while (scanner.hasNext()) {
                String sent = scanner.next();
                nword++;
                System.out.printf("%3d) %s%n", nword, sent);
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
    }

    /**
     * Specifying an empty-line regex as the delimiter allows you to read text by paragraphs.
     * The regular expression pattern specifies the multi-line flag, so use ^ and $ match at the beginning
     * and end of each line, rather than the whole input.
     *
     * @param filename
     */

    private static void eeout(String filename) {
        try (Scanner scanner = new Scanner(new File(filename));) {
            scanner.useDelimiter("(?m:^$)");
            int ntoken = 0;
            while (scanner.hasNext()) {
                String token = scanner.next();
                ntoken++;
                System.out.printf("%3d) %s%n", ntoken, token);
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
    }

    /**
     * To read the whole file in a single String, use the following.
     * The delimiter here is the regular expression for the beginning of the file.
     *
     * @param filename
     */
    private static void uuout(String filename) {
        try (Scanner scanner = new Scanner(new File(filename));) {
            scanner.useDelimiter("\\A");
            String all = scanner.next();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
    }

}
